/*********************************************************************************
 *      Copyright:  (C) 2016 Lu Zengmeng<1540999272@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  tcp.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(08/02/2016)
 *         Author:  Lu Zengmeng <1540999272@qq.com>
 *      ChangeLog:  1, Release initial version on "08/02/2016 08:09:55 AM"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
 
#include "tcp.h"
 
#include <stdlib.h>
/**************************************************************************************
 *  Description:
 *   Input Args:
 *  Output Args:
 * Return Value:
 *************************************************************************************/
int socket_init(void)
{
 
    int                    fd;
    struct sockaddr_in     serv_addr;

    //fp = fopen("/home/fs/qiang/getline/test/line.txt", "r");
    //export IP=192.168.1.153:8989
    char ip_str_default[]="192.168.1.8:8003";


    char *ip_str=getenv("IP");
    if(ip_str==NULL || strlen(ip_str)<9)
    {
        ip_str=ip_str_default;
    }

    char IPADDR[20]={0};
    char PORT_str[10]={0};
    int PORT;
    int i=0;
    for(i=0;i<strlen(ip_str);i++)
    {
        if(ip_str[i]==':')
            break;
    }
    memcpy(IPADDR,ip_str,i);
    memcpy(PORT_str,ip_str+i+1,strlen(ip_str)-i);
    PORT=atoi(PORT_str);
    printf("ip=%s,port=%s\n",IPADDR,PORT_str);




    bzero(&serv_addr,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port   = htons(PORT);


    if ((inet_pton(AF_INET,IPADDR,&serv_addr.sin_addr)) < 0)
    {
        perror("inet_pton");
        return -1;//exit(1);
    }
 
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        perror("socket");
        return -1;//exit(1);
    }
 
    if (-1 == connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)))
    {
        perror("connect");
        return -1;//exit(1);
    }
    printf("connect sucesseful\n");

    return fd;
}
     /* ----- End of socket_init()  ----- */